
const BASE_URL = "http://localhost:12345";
// const BASE_URL = "http://117.72.76.205:12345";
// const BASE_URL = "http://westudy.life:12345";

/**
 * 功能：发起http POST请求，请求参数为url，json数据，返回值为json
 */
export function httpPost(url: any, data: any) {
    var http = new XMLHttpRequest();
    url = BASE_URL + url;
    http.withCredentials = true;
    http.open("POST", url, false);
    http.setRequestHeader('content-type', 'application/json');
    http.send(JSON.stringify(data));
    var res = http.responseText;
    try {
        return JSON.parse(res);
    } catch (e) {
        return res;
    }
}

export function httpPostDownload(downloadUrl: any, fileName: any, data: any) {
  const http = new XMLHttpRequest();
  try {
    downloadUrl = BASE_URL + downloadUrl;
    http.open("POST", downloadUrl, true);
    http.setRequestHeader("content-type", "application/json");
    //设置期望的返回值类型
    http.responseType = "blob";
    //请求成功回调函数
    http.onload = function (oEvent) {
      if (http.status === 200) {
        try {
          if (fileName === undefined || fileName === null || fileName === "") {
            fileName = "未命名.txt";
          }
          var response = http.response;
          //数据转换为文件下载
          var elink = document.createElement("a");
          elink.download = fileName;
          elink.style.display = "none";
          var blob = new Blob([response]);
          elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();
          document.body.removeChild(elink);
        } catch (e) {
          console.log(e);
        }
      }
    };
    http.send(JSON.stringify(data));
  } catch (e) {
    console.log(e);
  }
}